package com.microservice.core.mybatis;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.*;
import java.util.*;


/**
 * 获取数据库表中所有表的字段元信息
 */
@Service
@Slf4j
public class TableMetadataService {

    private final DataSource dataSource;

    private final Map<String, List<String>> tableColumnsCache = new HashMap<>();

    public TableMetadataService(DataSource dataSource) {
        this.dataSource = dataSource;
        loadTableMetadata();
    }

    void loadTableMetadata() {
        try {
            Connection connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();

            // 获取所有表的名字
            ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                List<String> columns = getColumnsForTable(metaData, tableName);
                tableColumnsCache.put(tableName, columns);
            }
        } catch (SQLException e) {
            log.error("Error loading table metadata", e);
        }
    }

    private List<String> getColumnsForTable(DatabaseMetaData metaData, String tableName) throws SQLException {
        List<String> columns = new ArrayList<>();
        try (ResultSet columnsRS = metaData.getColumns(null, null, tableName, "%")) {
            while (columnsRS.next()) {
                columns.add(columnsRS.getString("COLUMN_NAME"));
            }
        }
        return columns;
    }

    public String getTableName(Class<?> clazz) {
        TableName annotation = clazz.getAnnotation(TableName.class);
        if (annotation != null) {
            return annotation.value();
        }
        return null;
    }

    public List<String> getColumnsForTable(String tableName) {
        return tableColumnsCache.getOrDefault(tableName, Collections.emptyList());
    }
}
